<template>
  <div class="parent">
    <img class="logoImage" src="../../assets/Logo/logo.png" alt="暂无图片" @click="router.push('/')">
    <el-text v-if="flag" class="logoText">找回密码</el-text>
    <el-text v-else class="logoText">重置密码</el-text>
    <el-text v-if="isFlag && flag" class="logoText1" size="default">已有账号？</el-text>
    <el-text v-else class="logoText1" size="default">{{ user.account }}</el-text>
    <el-text v-if="isFlag && flag" class="loginText" @click="toLogin">马上登录</el-text>
    <el-text v-else class="loginText" @click="exitLogin">退出</el-text>
    <el-card class='ForgetPwdCard'>
      <div class="image-content" v-if="flag">
        <!--找回密码界面-->
        <el-form :model="user" v-if="isFlag" label-width="auto" style="max-width: 600px" :rules="rules" ref="formRef">
          <el-form-item prop="account">
            <el-input class="ForgetPwdInput" maxlength="11" v-model="user.account" type="text" size="large"  placeholder="手机"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-input class="ForgetPwdInput" maxlength="6" type="text" size="large" v-model="user.code" style="margin-bottom: 20px;" placeholder="验证码">
              <template #suffix>
                |&nbsp;<el-button class="custom-suffix" @click="send_sms">{{ user.sms_btn_text1 }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button color="#7753ff" size="large" style="width: 100%;border-radius: 20px 20px 20px 20px;" @click="ForgetPwd">找回密码</el-button>
          </el-form-item>
        </el-form>
        <!--重置密码后，展示界面-->
        <div v-if="!isFlag">
          <img class="ForgetPwdImage" src="../../assets/ForgetSuccess.png"/>
          <el-text class="ForgetPwdText">找回密码成功</el-text>
          <el-text class="ForgetPwdTip">{{ user.account }}<el-text>，欢迎回来！</el-text></el-text>
          <el-button class="ForgetPwdButton" color="#7753ff" size="large" @click="toLogin">立即登录</el-button>
        </div>
      </div>
      <div class="image-content" v-else>
        <!--重置密码前界面-->
        <el-text >{{ user.account }}，请设置您的新密码</el-text>
        <el-form :model="user" v-if="isFlag" label-width="auto" style="max-width: 600px" :rules="rules" ref="formRef">
          <el-form-item prop="password">
            <el-input class="ForgetPwdInput" maxlength="16" v-model="user.password" type="password" show-password size="large"  placeholder="新密码"/>
          </el-form-item>
          <el-form-item prop="re_password">
            <el-input class="ForgetPwdInput" maxlength="16" type="password" size="large" v-model="user.re_password" show-password style="margin-bottom: 20px;" placeholder="再次输入"/>
          </el-form-item>
          <el-form-item>
            <el-button color="#7753ff" size="large" style="width: 100%;border-radius: 20px 20px 20px 20px;" @click="resetPwd">密码重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch} from "vue";
import user from "../../api/user"
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router";
const router = useRouter()

let is_check_info =ref(false)

const formRef = ref(null);

// 验证码是否校验成功
let flag = ref(true)
// 密码是否找回成功
let isFlag = ref(true)

// 注册手机号等校验
const rules = {
  account: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  re_password: [
    { required: true, message: '请输入再次确认密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
};

// 自定义校验函数
function validatePassword(rule, value, callback) {
  if (value.length < 8 || value.length > 16) {
    return callback(new Error('密码长度必须在8到16位之间'));
  }
  const regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d]).+$/;
  if (!regex.test(value)) {
    return callback(new Error('密码必须包含字母、数字和特殊字符'));
  }
  callback();
}

// 找回密码点击事件
const ForgetPwd = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 发送请求
      user.forget().then(response=>{

        console.log('-----找回密码验证成功----');
        console.log(response);

        ElMessage.success("找回密码验证成功！");
        user.code = ''
        flag.value = false
      }).catch(error=>{
        // 注册失败！
        console.log('-----找回密码验证失败----');
        console.log(error);
        ElMessage.success(`找回密码验证失败！错误信息：${error?.response?.data?.message}`);
      })
    } else {
      ElMessage.error('输入有误，请重试！');
      return false;
    }
  });
};

// 重置密码点击事件
const resetPwd=()=>{
  formRef.value.validate((valid) => {
    if (valid) {
      if (user.password !== user.re_password) {
        ElMessage.error('错了哦，密码和确认密码不一致！');
        return false
      }

      // 发送请求
      user.reset_Pwd().then(response=>{

        console.log('-----密码重置成功----');
        console.log(response);

        ElMessage.success("密码重置成功！");

        flag.value = true
        isFlag.value = false
      }).catch(error=>{
        // 注册失败！
        console.log('-----密码重置失败----');
        console.log(error);
        ElMessage.success(`密码重置失败！错误信息：${error?.response?.data?.message}`);
      })
    } else {
      ElMessage.error('输入有误，请重试！');
      return false;
    }
  });
}

// 发送短信
const send_sms = ()=> {
  // 手机号二次校验
  if (!/1[3-9]\d{9}/.test(user.account)) {
    ElMessage.error("手机号格式有误！")
    return false
  }

  // 判断是否处于短信发送的冷却状态
  if (user.is_send) {
    ElMessage.error("短信发送过于频繁！")
    return false
  }

  let time = user.sms_interval;

  // 发送短信请求
  user.forgetPwd_send_sms().then(response=>{
    ElMessage.success("短信发送中，请留意您的手机！");
    // 发送短信后进入冷却状态
    user.is_send = true;
    // 冷却倒计时
    clearInterval(user.interval);
    user.interval = setInterval(()=> {
      if (time < 1) {
        user.is_send = false  // 退出短信发送的冷却状态
        user.sms_btn_text1 = "点击获取验证码"
      } else {
        time -= 1;
        user.sms_btn_text1 = `${time}秒后重新获取`;
      }
    },1000)
  }).catch(error=>{
    console.log(error);

    ElMessage.error(error?.response?.data?.message);
    time = error?.response?.data?.interval;
    // 冷却倒计时
    clearInterval(user.interval);
    user.interval = setInterval(()=>{
      if(time<1){
        // 退出短信发送的冷却状态
        user.is_send = false
        user.sms_btn_text1 = "点击获取验证码"
      }else{
        user.is_send = true;
        time-=1;
        user.sms_btn_text1 = `${time}秒后重新获取`;
      }
    }, 1000)

  })
}

const toLogin=()=>{
  router.push('/login')
}

const exitLogin=()=>{
  window.location.href = 'https://www.dxy.cn/'
}


</script>

<style scoped>
.logoImage{
  position: absolute;
  top: 10%;
  left: 22%;
  display:flex;
  width: 150px;
  height: 80px;
  transform: translate(-50%, -50%);
}

.logoText{
  position: absolute;
  top: 10%;
  left: 33%;
  display:flex;
  transform: translate(-50%, -50%);
  font-size: 25px;
  color: black;
}

.logoText1{
  position: absolute;
  top: 10%;
  right: 18%;
  display:flex;
  transform: translate(-50%, -50%);
}

.loginText{
  position: absolute;
  top: 10%;
  right: 15%;
  display:flex;
  transform: translate(-50%, -50%);
  color: #7753ff;
}


.ForgetPwdCard{
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 68%;
  height: 80%;
  border-radius: 8px;

}

.image-content {
  /*margin: auto;*/
  margin-top: 10%;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}


.ForgetPwdInput >>> .el-input__wrapper {
  width: 80%;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 20px 20px 20px 20px; /* 这里的20px可以根据需要修改成任何你想要的大小 */
  background-color: rgba(248, 248, 248);
}

.ForgetPwdInput >>> .el-input__inner {
  /*background-color: rgba(0, 0, 0, 0.1);*/
}

.ForgetPwdImage{
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 10%;
}

.ForgetPwdText{
  position: absolute;
  top: 43%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 25px;
  font-weight: bold;
  color: black;
}
.ForgetPwdTip{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: black;
}

.ForgetPwdButton{
  position: absolute;
  top: 58%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 30%;
  border-radius: 20px 20px 20px 20px;
}

.custom-suffix {
  display: flex;
  align-items: center;
  padding-right: 10px;
  color: #7753ff;
  border: none;
  background-color: rgba(0, 0, 0, 0);
}
</style>